#include <stdio.h>
#include <stdlib.h>
#include "router.h"
#include "pesi_string.h"

namespace PESI {

Router::Router()
{
}
Router::~Router()
{
  for( int i = 0, len = _routes.size(); i < len; ++i ){
    delete _routes[i];
  }
  _routes.clear();
}

bool Router::load(const char *config_file)
{
  FILE *input = fopen(config_file,"rb");
  char * line = NULL;
  size_t len = 0;
  ssize_t read;

  if( !input ){ return false; }

  char *mark = NULL;
  char *pmark = NULL;
  std::string context, host, port, match, buf, val;
  std::vector<std::string> parts; 

  while( (read = getline(&line, &len, input)) != -1 ){
    pmark = line;
    while( (mark = strstr(pmark,":")) ){
      len = mark - pmark;
      if( len == 0 ){ break; }
      buf = std::string(pmark,len);
      buf = PESI::trim(buf);
      //printf( "key string: %s\n", buf.c_str() );
      parts.push_back( buf );
      pmark = mark + 1;
    }

    if( !mark && pmark ){
      len = strlen(pmark);
      buf = std::string(pmark,len); // strip trailing \n
      buf = PESI::trim(buf);
      if( buf.size() > 0 ){
     //   printf( "value string: %s\n", buf.c_str() );
        parts.push_back( buf );
      }
    }

    //printf( "parts: %d\n", parts.size() );

    if( parts.size() == 1 ){
      //printf( "found context: %s, (host:%s, port:%s, match:%s)\n", context.c_str(), host.c_str(), port.c_str(), match.c_str() );
      if( !context.empty() && !host.empty() && !port.empty() && (context == "default" || !match.empty()) ){
        this->_routes.push_back( new Route(context, host, atoi(port.c_str()), match) );
        host.clear();
        port.clear();
        match.clear();
        context.clear();
      }
      context = parts[0];
    }
    else if( parts.size() == 2 ){
      buf = parts[0];
      val = parts[1];
      if( buf == "host" ){
        host = val;
      }
      else if( buf == "port" ){
        port = val;
      }
      else if( buf == "match_url" ){
        match = val;
      }
    }

    parts.clear();
  }
  //printf( "final context: %s, (host:%s, port:%s, match:%s)\n", context.c_str(), host.c_str(), port.c_str(), match.c_str() );
  if( !context.empty() && !host.empty() && !port.empty() && (context == "default" || !match.empty()) ){
    this->_routes.push_back( new Route(context, host, atoi(port.c_str()), match) );
  }

  fclose(input);

  for( int i = 0, len = _routes.size(); i < len; ++i ){
    printf( "%s: %s:%d => %s\n", _routes[i]->context(), _routes[i]->host(), _routes[i]->port(), _routes[i]->match() );
  }
}

}
